<?php
namespace Common\Model;

class SiterModel extends UserModel {
    const TYPE = 1; //1表示站长

    public function getById($id) {
        $expr = array(
            'type' => self::TYPE,
            'id'   => $id,
        );

        return $this->where($expr)->find();
    }

    public function save2($d) {
        $id = empty($d['id']) ? 0 : (int)$d['id'];

        if(!empty($d['bank'])) {
            $d['bank'] = strtolower($d['bank']);
        }

        $d['opts'] = $this->buildOpts($d);

        try {
            $m = D('User');
            if (($r = $m->save2($d)) === false) {
                throw new \Exception('保存站长数据出错');
            }

            if (empty($d['id'])) {
                $id = $r;
            }
        } catch(Exception $e) {
            throw new \Exception($e->getMessage());
        }

        try {
            cacheApi('siter', [
                'a'  => (empty($d['id']) ? 'add' : 'modify'),
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($id) {
        $id = (int)$id;

        if (D('Site')->where(['uid' => $id])->find()) {
            throw new \Exception('此站长还有网站，不能删除此站长');
        }

        if (D('Zone')->where(['uid' => $id])->find()) {
            throw new \Exception('此站长还有广告位，不能删除此站长');
        }

        $expr = [            
            'type' => self::TYPE,
            'id'   => $id,
        ];

        $this->where($expr)->delete();

        try {
            cacheApi('siter', [
                'a'  => 'del',
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    /**
     * _options_filter()中设置的有条件，所以在Model::save()方法中不会再设置以主键为条件
     */
    protected function _before_update(&$data, &$options) {
        if(empty($options['where'][$this->getPk()]) && !isset($data[$this->getPk()])) {
            return false;
        }

        if(isset($options['where']) && !array_key_exists($this->getPk(), $options['where'])) {
            $options['where'][$this->getPk()] = $data[$this->getPk()];
        }

        return true;
    }

    protected function _options_filter(&$options) {
        if(!$loginUser = C('RUN_LOGIN_USER')) {
            exit('NO LOGIN');
        }

        if($loginUser['type'] == 3) {
            $options['where'] = isset($options['where']) ? $options['where'] : array();
            $options['where']['service_id'] = $loginUser['uid'];

            return true;
        }
    }

    protected function _after_find(&$resultSet,$options) {
        if ($a = $this->parseOptsField($resultSet['opts'])) {
            $resultSet = array_merge($resultSet, $a);
        }

        return true;
    }

    /**
     * buildDeduct
     * 组装扣量数据成json格式，以便保存至postgresql jsonb字段中
     *
     * $d中键名以deduct_开头的就是扣量相关的设置
     *
     * @param mixed $d
     * @return void
     */
    protected function buildDeduct($d) {
        $prefix    = 'deduct_';
        $prefixLen = strlen($prefix);
        $r = [];

        foreach ($d as $k => $v) {
            if (substr($k, 0, $prefixLen) == $prefix) {
                $r[$k] = $v;
            }
        }

        return ['deduct' => $r];
    }

    /**
     * buildOpts
     * 组装表中opts字段值
     *
     * @param mixed $d
     * @return void
     */
    public function buildOpts($d) {
        $r = [];

        /**
         * 找出opts原值，然后在后面合并
         */
        if (!empty($d[$this->pk])) {
            if ($tmp = $this->field('opts')->where([$this->pk => $d[$this->pk]])->find()) {
                if ($tmp2 = json_decode($tmp['opts'], true)) {
                    $r = $tmp2;
                }
            }
        }

        if ($deduct = $this->buildDeduct($d)) {
            $r = array_merge($r, $deduct);
        }

        return json_encode($r);
    }

    public function changeStatus($id, $s) {
        $r = parent::changeStatus($id, $s);

        try {
            cacheApi('siter', [
                'a'  => 'modify',
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

}
